package com.asus.oplay.asusuitest;

import java.io.File;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.io.DataOutputStream;
import java.io.BufferedReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import org.apache.http.util.EncodingUtils;


public class UsbReceiver extends Service{
    private String TAG="UsbReceiver";
    private BroadcastReceiver mReceiver;
    private boolean blogusb = false;
    private boolean bmediausb = false;
    private boolean bconfigusb = false;
    private String strlogusb;
    private String strmediausb;
    private String strconfigusb;
    private boolean bfirst = true;
    
    private boolean bapkusb = false;
    private String strapkdir;	////[Sonic+20140228,For ASUSUITest]
    private String[] strAllApk;	//// 记录指定目录下的apk文件
    
    

    private boolean isBTTestMode(File configfile)
    {
            Log.i(TAG,"isBTTestMode");
            String str="";
            String modefile="";
            try {
                FileInputStream fos;
                fos = new FileInputStream(configfile);
                byte [] buffer = new byte[fos.available()];
                fos.read(buffer);
                str = EncodingUtils.getString(buffer, "UTF-8");
                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                Log.e(TAG,"CheckConfigFileSystem FileNotFoundException");
                e.printStackTrace();
            } catch (IOException e) {
                Log.e(TAG,"CheckConfigFileSystem IOException");
                e.printStackTrace();
            }
            if(str == null || str.equalsIgnoreCase(""))
            {
                Log.e(TAG,"Read config usb file error,Exit.");
                return false;
            }
            else
            {

                if(str.indexOf("MODE:") != -1)
                {
                    if(str.indexOf("\n",str.indexOf("MODE:")) != -1)
                        modefile = str.substring(str.indexOf("MODE:")+5, str.indexOf("\n",str.indexOf("MODE:")));
                    else
                        modefile = str.substring(str.indexOf("MODE:")+5);
                }
                if(modefile.equalsIgnoreCase(""))
                {
                    modefile = "PCBA";
                    Log.i(TAG,"Get modefile error");
                }
                Log.i(TAG,"Facotry Test Mode: " + modefile);

                if(modefile.equalsIgnoreCase("BTTEST")) {
                        return true;
                }
                return false;

            }

    }

    public Boolean disableBluetooth() {
        BluetoothAdapter adpater=BluetoothAdapter.getDefaultAdapter();
        if(adpater.isEnabled())
        {
            Log.i(TAG,"disableBluetooth");
            adpater.disable();
        }

        return !adpater.isEnabled();
    }

    public Boolean execCommands(String... command) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process process = rt.exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());

            for(int i = 0; i < command.length; i++) {
                os.writeBytes(command[i] + "\n");
                os.flush();
            }
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (IOException e) {
            return false;
        } catch (InterruptedException e) {
            return false;
        }
        return true;
    }
    
    ////[Sonic+20140228,For ASUSUITest]
    public void installAPKBatch(final String apkfile){
    	Log.d(TAG,"sonic==test==installAPKBatch=apkfile="+apkfile);
        new Thread(){
          public void run() {
              Process install = null;
              try {
                  //安装apk命令
                  install = Runtime.getRuntime().exec("pm install " + apkfile); 
                  install.waitFor();
              } catch (Exception e) {
                  e.printStackTrace();
              }finally{
                  if (install != null) {
                      install.destroy();
                  }
              }
          }  
        }.start();      
    }
    ////[Sonic-20140228]

    public void enterBTTestMode() {
            String[] commands = {
            "su -c autobt testmode --power 6"
            };

        execCommands(commands);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"onCreate");
    }

    @Override
    public int onStartCommand(Intent intent,int flag,int startid) {
        Log.d(TAG, "onStartCommand");

        //Toast.makeText(this.getApplicationContext(), "Log USB Found,wait Media USB.",Toast.LENGTH_LONG).show();
        //		Intent ASUSUItest=new Intent(this.getApplicationContext(),ASUSUITest.class);
        //		ASUSUItest.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //		this.getApplicationContext().startActivity(ASUSUItest);

        if(bfirst == false)
            return START_NOT_STICKY;

        bfirst = false;

        mReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {

                if(intent.getAction().equalsIgnoreCase(Intent.ACTION_MEDIA_MOUNTED) )
                {
                    Log.d(TAG,"onReceive path:"+intent.getData().getPath());
                    File mediafile = new File(intent.getData().getPath()+"/.factorymode_media/.mediausb");
                    File configfile = new File(intent.getData().getPath()+"/.factorymode_config/.configusb");
                    File logfile = new File(intent.getData().getPath()+"/.factorymode_log/.logusb");
                    
                    File apkfile = new File(intent.getData().getPath()+"/.factorymode_install");////[Sonic+20140228,For ASUSUITest]
                    
                    String alerstr;
                    if(configfile != null && configfile.exists() && isBTTestMode(configfile))
                    {
                        if(disableBluetooth())
                            Toast.makeText(context, "藍牙已關閉，請進入測試模式", 60000).show();
                        else
                            Toast.makeText(context, "關閉藍牙失敗", 5000).show();
                        return;
                    }
                    
//                    ////[Sonic+20140228,For ASUSUITest]
//                    if (apkfile != null && apkfile.exists())
//                    {
//                    	Log.d(TAG,"apkfile exists");
//                    	bapkusb = true;
//                    	
//                        strapkdir = intent.getData().getPath()+"/" + ".factorymode_install/";
//                        strAllApk = new File(strapkdir).list();
//                        Log.d(TAG,"sonic==test==strAllApk[0]="+strapkdir+strAllApk[0]);
//                        
//                        for (int k = 0; k < strAllApk.length; k++) {
//                        	installAPKBatch(strapkdir+strAllApk[k]);
//                		}
//                    }
//                    ////[Sonic-20140228]
                    
                    
                    ////sonic for test
                    
                    if (apkfile != null && apkfile.exists())
                    {
                    	Log.d(TAG,"sonic==test==apkfile exist");
                    	
                    	
                    }
                    ////sonic for test
                    
                    if(mediafile != null && logfile != null && configfile != null)
                    {
                        if(mediafile.exists() && logfile.exists() && configfile.exists())
                        {
                            Log.d(TAG,"All exists,error");
                            return;
                        }

                        if(mediafile.exists())
                        {
                            Log.d(TAG,"mediafile exists");
                            bmediausb = true;
                            strmediausb =intent.getData().getPath()+"/";
                        }

                        if(logfile.exists())
                        {
                            Log.d(TAG,"logfile exists");
                            blogusb = true;
                            strlogusb =intent.getData().getPath()+"/";
                        }

                        if(configfile.exists())
                        {
                            Log.d(TAG,"configfile exists");
                            bconfigusb = true;
                            strconfigusb =intent.getData().getPath()+"/";
                        }

                        alerstr=" ";

                        if(!bmediausb)
                            alerstr = alerstr+ "Media USB ";
                            //Toast.makeText(context, "Log USB Found,wait Media USB.",Toast.LENGTH_LONG).show();
                        if(!bconfigusb)
                            alerstr = alerstr+ "Config USB ";

                        if(!blogusb)
                            alerstr = alerstr+ "Log USB ";
                            //Toast.makeText(context, "Media USB Found,wait Log USB.",Toast.LENGTH_LONG).show();

                        if(blogusb && bmediausb && bconfigusb)
                        {
                            Log.d(TAG,"All exists");

                            bmediausb = false;
                            blogusb = false;
                            bconfigusb = false;
                            

                            Intent ASUSUItest=new Intent(context,ASUSUITest.class);
                            ASUSUItest.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            ASUSUItest.putExtra("usbmedia", strmediausb);
                            ASUSUItest.putExtra("usblog", strlogusb);
                            ASUSUItest.putExtra("usbconfig", strconfigusb);
                            context.startActivity(ASUSUItest);
                        }else
                            Toast.makeText(context, "Wait " + alerstr,Toast.LENGTH_LONG).show();
                    }
                }
            }

        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addDataScheme("file");
        registerReceiver(mReceiver, filter);

        File file = new File("/mnt/usbdrive/");
        if(file!=null && file.exists())
        {
            File[] filelist = file.listFiles();

            Log.d(TAG,"/mnt/usbdrive/:"+Integer.toString(filelist.length));

            for(int i=0;i<filelist.length;i++)
            {
                Log.d(TAG,"/mnt/usbdrive/:"+filelist[i].getPath());
                File mediafile = new File(filelist[i].getPath()+"/.factorymode_media/.mediausb");
                File logfile = new File(filelist[i].getPath()+"/.factorymode_log/.logusb");
                File configfile = new File(filelist[i].getPath()+"/.factorymode_config/.configusb");
                
                ////[Sonic+20140228,For ASUSUITest]
                File apkfile = new File(filelist[i].getPath()+"/.factorymode_install");
                
//                if (apkfile != null && apkfile.exists())
//                {
//                	Log.d(TAG,"apkfile exists");
//                	bapkusb = true;
//                	
//                    strapkdir = filelist[i].getPath()+"/" + ".factorymode_install/";
//                    strAllApk = new File(strapkdir).list();
//                    Log.d(TAG,"sonic==test==strAllApk[0]="+strapkdir+strAllApk[0]);
//                    
//                    for (int k = 0; k < strAllApk.length; k++) {
//                    	installAPKBatch(strapkdir+strAllApk[k]);
//            		}
//                }
                ////[Sonic-20140228]
                
                String alerstr;
                if(configfile != null && configfile.exists() && isBTTestMode(configfile))
                {
//					if(disableBluetooth())
//						Toast.makeText(getApplicationContext(), "藍牙已關閉，請進入測試模式", 5000).show();
//					else
//						Toast.makeText(getApplicationContext(), "關閉藍牙失敗", 5000).show();
                }
                if(mediafile != null && logfile != null && configfile != null)
                {
                    if(mediafile.exists() && logfile.exists() && configfile.exists())
                    {
                        Log.d(TAG,"All exists,error");
                    }
                    else
                    {
                        if(mediafile.exists())
                        {
                            Log.d(TAG,"mediafile exists");
                            bmediausb = true;
                            strmediausb =filelist[i].getPath()+"/";
                        }

                        if(logfile.exists())
                        {
                            Log.d(TAG,"logfile exists");
                            blogusb = true;
                            strlogusb =filelist[i].getPath()+"/";
                        }

                        if(configfile.exists())
                        {
                            Log.d(TAG,"configfile exists");
                            bconfigusb = true;
                            strconfigusb =filelist[i].getPath()+"/";
                        }

                        alerstr=" ";

                        if(!bmediausb)
                            alerstr = alerstr+ "Media USB ";
                            //Toast.makeText(context, "Log USB Found,wait Media USB.",Toast.LENGTH_LONG).show();
                        if(!bconfigusb)
                            alerstr = alerstr+ "Config USB ";

                        if(!blogusb)
                            alerstr = alerstr+ "Log USB ";
                            //Toast.makeText(context, "Media USB Found,wait Log USB.",Toast.LENGTH_LONG).show();

                        if(blogusb && bmediausb && bconfigusb)
                        {
                            Log.d(TAG,"All exists");

                            bmediausb = false;
                            blogusb = false;
                            bconfigusb = false;

                            Intent ASUSUItest=new Intent(this.getApplicationContext(),ASUSUITest.class);
                            ASUSUItest.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            ASUSUItest.putExtra("usbmedia", strmediausb);
                            ASUSUItest.putExtra("usblog", strlogusb);
                            ASUSUItest.putExtra("usbconfig", strconfigusb);
                            this.getApplicationContext().startActivity(ASUSUItest);

                            return START_NOT_STICKY;
                        }
                    }
                }
            }
        }

        return START_NOT_STICKY;
    }
}
